package fr.cephb.joperon.webapp.jpa;


import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

import javax.persistence.Table;

/**
 * User
 * @author lindenb
 *
 */
@Entity
@Table(name="ACCESS",schema="OPERON")
@NamedQueries(value={
@NamedQuery(
	    name="access.users.byProject",
	    query="SELECT T.user FROM Access T WHERE T.project = :project"
	    ),
@NamedQuery(
	    name="access.byUserIdAndProject",
	    query="SELECT T FROM Access T WHERE T.project = :project and T.user.id = :userId"
	    )    
})
public class Access
	{
	private int id;
	private User user;
	private String project=null;
	private boolean administrator;
	private boolean writer;
	
	public Access()
		{
		
		}
	
	
	 @Id
     @Column(name="ID")
     @GeneratedValue(strategy=GenerationType.AUTO)
     public int getId() {
             return id;
     }

     @SuppressWarnings("unused")
	private void setId(int id) {
             this.id = id;
     }

     @ManyToOne(cascade={CascadeType.REMOVE})
     @JoinColumn(name="user_id")
     public User getUser() {
             return user;
     }
     
     public void setUser(User user) {
             this.user = user;
     	}
     
    
     public void setProject(String project) {
		this.project = project;
	}
     
     
     @Column(name="project_id",length=50,nullable=false,updatable=false)
     public String getProject() {
		return project;
	}
 
     
	@Override
	public int hashCode() {
		return getId();
		}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		return getId()==(Access.class.cast(obj).getId());
		}
	
	@Override
		public String toString() {
			return "Access{id:"+getId()+",login:"+getUser()+"}";
			}
	
	
	
	public void setAdministrator(boolean administrator) {
		this.administrator = administrator;
		}
	
	@Column(name="is_admin")
	public boolean isAdministrator()
		{
		User user=getUser();
		if(user!=null)
			{
			if(user.isRoot()) return true;
			if(user.isAnonymous()) return false;
			}
		return administrator;
		}
	

	public void setWriter(boolean writer)
		{
		
		this.writer = writer;
		}
	
	@Column(name="is_writer")
	public boolean isWriter()
		{
		if(isAdministrator()) return true;
		User user=getUser();
		if(user!=null)
			{
			if(user.isAnonymous()) return false;
			}
		return writer;
		}
	
}

